/*
 *	ftrace.cc: 
 *	option parsing and main task start.
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "task.h"


static void usage() 
{
	printf(	"Trace command or running process and collect file i/o statistics\n"
		"Usage: frace [-vh] [-p pid] [command [args..]]\n"
		" -h:		this screen\n"
		" -v:		verbose mode, report file i/o events when they occur\n"
		" -p pid:	attach to running process\n"
		" command args:	run and trace command with specified arguments\n"
	);
}


int main(int argc, char** argv) 
{
	int verbose = 0;
	pid_t pid = -1; // if it will be >= 0 after getopt loop then we have a task to attach.

	int opt;	
	while((opt = getopt(argc, argv, "hvp:")) != -1) {
		switch (opt) {
		case 'h': 
			usage(); 
			return EXIT_SUCCESS;

		case 'v':
			verbose++;
			break;

		case 'p':
			pid = atoi(optarg);
			if(pid < 0) {
				fprintf(stderr, "Error: Invalid process id\n");
				return EXIT_FAILURE;
			} else if (pid == getpid()) {
				fprintf(stderr, "Error: Can't trace myself\n");
				return EXIT_FAILURE;
			}
			break;

		default:
			fprintf(stderr, "Error: Invalid option\n");
			usage();
			return EXIT_FAILURE;
		};
	} 

	TraceTask task;
	if(pid < 0) {
		if(optind == argc) {
			fprintf(stderr, "Error: Trace command or pid not specified\n");
			usage();
			return EXIT_FAILURE;
		}
		
		const char* command = argv[optind];
		char** args = &argv[optind];
		task.start(command, args);
	} else {
		task.attach(pid);
	}
	
	if(task.state() != TraceTask::kStopped) {
		return EXIT_FAILURE;
	}

	return task.trace();
}


